import { ref, watch, nextTick } from 'vue';

interface CaptchaOptions {
  length?: number;
  fontSize?: number;
  lineCount?: number;
}

export function useCaptcha(options: CaptchaOptions = {}) {
  const {
    length = 4,
    fontSize = 24,
    lineCount = 5
  } = options;

  const canvasRef = ref<HTMLCanvasElement | null>(null);
  const currentCaptchaCode = ref<string>('');

  // 验证码字符集
  const codeChars = 'ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz0123456789';

  // 获取随机颜色
  const getRandomColor = (): string => {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    return `rgb(${r},${g},${b})`;
  };

  // 生成随机验证码字符串
  const generateCode = (): string => {
    let verifyCodeStr = '';
    for (let i = 0; i < length; i++) {
      const charIndex = Math.floor(Math.random() * codeChars.length);
      verifyCodeStr += codeChars[charIndex];
    }
    drawCode(verifyCodeStr);
    return verifyCodeStr;
  };

  // 绘制验证码到 canvas
  const drawCode = (code: string): void => {
    const canvas = canvasRef.value;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    // 清除画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 设置字体和颜色
    ctx.font = `${fontSize}px Arial`;
    ctx.fillStyle = getRandomColor();

    // 计算字符间距
    const charSpacing = (canvas.width - 20) / code.length;

    // 绘制验证码字符
    for (let i = 0; i < code.length; i++) {
      const x = 10 + i * charSpacing;
      const y = canvas.height / 2 + Math.random() * 10 - 5;
      ctx.fillText(code[i], x, y);
    }

    // 绘制干扰线
    for (let i = 0; i < lineCount; i++) {
      ctx.beginPath();
      ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
      ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
      ctx.strokeStyle = getRandomColor();
      ctx.lineWidth = 1;
      ctx.stroke();
    }
  };

  // 刷新验证码
  // 定义一个名为 refreshCode 的常量，它是一个箭头函数，用于刷新验证码
  const refreshCode = () => {
    // 调用 generateCode 函数生成一个新的验证码，并将其赋值给 newCode 常量
    const newCode = generateCode();
    currentCaptchaCode.value = newCode;
  };

  // 响应式调整画布大小
  const resizeCanvas = () => {
    const canvas = canvasRef.value;
    if (canvas) {
      canvas.width = canvas.offsetWidth;
      canvas.height = canvas.offsetHeight;
      if (currentCaptchaCode.value) {
        drawCode(currentCaptchaCode.value);
      }
    }
  };

  watch(canvasRef, async () => {
    await nextTick();
    resizeCanvas();
    const newCode = generateCode();
    currentCaptchaCode.value = newCode;
  });

  window.addEventListener('resize', resizeCanvas);

  return {
    canvasRef,
    currentCaptchaCode,
    refreshCode
  };
}